package main

import (
	"fmt"
	"log"
	"net/http"

	"gitee.com/kun_liu/to-log/app/middleware"
	"gitee.com/kun_liu/to-log/app/models"
	"gitee.com/kun_liu/to-log/app/routes"
	"gitee.com/kun_liu/to-log/pkg/database"
	"github.com/gin-gonic/gin"
	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

func main() {
	// 初始化数据库
	db, err := gorm.Open(sqlite.Open("tolog.db"), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// 自动迁移数据库模型
	db.AutoMigrate(
		&models.User{},
		&models.Post{},
		&models.Comment{},
		&models.Category{},
		&models.Tag{},
		&models.Option{},
		&models.Meta{},
	)

	// 设置数据库连接
	database.SetDB(db)

	// 创建Gin实例
	r := gin.Default()

	// 注册中间件
	r.Use(middleware.Session())
	r.Use(middleware.CurrentUser())

	// 设置静态文件目录
	r.Static("/static", "./static")

	// 设置模板
	r.LoadHTMLGlob("views/*")

	// 注册路由
	routes.RegisterRoutes(r)

	// 启动服务器
	port := 8080
	fmt.Printf("Server is running at http://localhost:%d\n", port)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", port), r); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
